<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
    <el-form-item label="图标排序" prop="sort">
      <el-input v-model="ruleForm.sort"></el-input>
    </el-form-item>
    <el-form-item label="图标标题" prop="mobileTitle">
      <el-input v-model="ruleForm.mobileTitle"></el-input>
    </el-form-item>
    <el-form-item label="上传图标" prop="mobileIcon">
      <el-upload
        class="upload-demo"
        action="http://backendapp.vacomall.cn/index/add"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :multiple="false"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-form-item>
    <el-form-item label="是否展示" prop="isShow">
      <el-radio-group v-model="ruleForm.isShow">
        <el-radio label="1">展示</el-radio>
        <el-radio label="-1">不展示</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="类目深度" prop="id">
      <el-select v-model="ruleForm.categoryDeeper" placeholder="类目深度" @change="change"
                 clearable
                 :disabled="formType === 'update'"
      >
        <el-option key='index'
                   v-for="(item,index) in options1"
                   :label="item.label"
                   :value="item.value"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="类目" prop="categoryDeeper" style="width: 100%" v-if="formType === 'create'">
      <el-cascader
        style="width:330px"
        placeholder="请选择"
        :options="options"
        :disabled="ruleForm.categoryDeeper.length===0"
        filterable
        @active-item-change="handleItemChange"
        v-model="ruleForm.id"
        clearable
        :props="props">
      </el-cascader>
    </el-form-item>
    <el-form-item label="类目" prop="id" style="width: 100%" v-else>
      <div>{{this.ruleForm.cateText}}</div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="formType==='update'?updateForm('ruleForm'):submitForm('ruleForm')"
                 :loading="submitStatus">确定
      </el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
    </el-form-item>
  </el-form>
</template>
<script>
  import * as types from '../../store/mutations-type'
  import api from '../../store/api'
  var format = require('../../util/util')
  import axios from 'axios'
  export default {
    data () {
      var validateId = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('请选择类目'))
        } else {
          callback()
        }
      }
      return {
        handle: 'add',
        submitStatus: false,
        /* ruleForm: {
         sort: '',
         mobileTitle: '',
         mobileIcon: '',
         isShow: '1',
         categoryDeeper:'',
         id: []
         }, */
        value: '',
        rules: {
          sort: [
            {required: true, message: '请请输入图标排序', trigger: 'blur'},
            {pattern: /^[1-9]\d*$/, message: '输入1-9数字'}
          ],
          mobileTitle: [
            {required: true, message: '请输入图标标题', trigger: 'blur'},
            {pattern: /^(([^^<>%&',;=?$"':#!~\][{}\\/`|])*)$/, message: '不能输入特殊字符'}
          ],
          mobileIcon: [
            {required: true, message: '请上传图标', trigger: 'blur'}
          ],
          isShow: [
            {required: true, message: '请选择状态', trigger: 'blur'}
          ],
          categoryDeeper: [
            {required: true, message: '请选择类目深度', trigger: 'blur'}
          ],
          id: [
            {required: true, validator: validateId, trigger: 'blur'}
          ]
        },
        flag: {
          a: '',
          b: ''
        },
        options: [],
        props: {
          value: 'id',
          label: 'categoryName',
          children: 'child'
        },
        options1: [{
          value: '1',
          label: '一级类目'
        }, {
          value: '2',
          label: '二级类目'
        }, {
          value: '3',
          label: '三级类目'
        }]
      }
    },
    props: ['formType', 'getTreeData', 'ruleForm'],
    methods: {
      handlePreview (file) {
        console.log(file)
      },
      handleSuccess (result) {
        this.ruleForm.mobileIcon = result.data
      },
      handleRemove (file, fileList) {
        console.log(file)
      },
      handleItemChange (val) {
        var len = val.length - 1
        if (val.length === 1) {
          this.options.map((item, index) => {
            if (item.id === val[len]) {
              this.flag.a = index
              return
            }
          })
          this.getCategoryTree(val[len])
            .then(result => {
              if (this.ruleForm.categoryDeeper === '2') {
                let array = result.map((obj, index) => {
                  delete obj.child
                  return obj
                })
                this.options[this.flag.a].child = array
              } else {
                this.options[this.flag.a].child = result
              }
            })
        } else if (val.length === 2) {
          this.options[this.flag.a].child.map((item, index) => {
            if (item.id === val[len]) {
              this.flag.b = index
              return
            }
          })
          this.getCategoryTree(val[len])
            .then(result => {
              this.options[this.flag.a].child[this.flag.b].child = result
            })
        }
        /* var len = val.length - 1
         if (val.length === 1) {
         this.options.map((item, index) => {
         if (item.id === val[len]) {
         this.flag.a = index
         return
         }
         })
         this.getCategoryTree(val[len])
         .then(result => {
         this.options[this.flag.a].child = result
         })
         } else if (val.length === 2) {
         this.options[this.flag.a].child.map((item, index) => {
         if (item.id === val[len]) {
         this.flag.b = index
         return
         }
         })
         this.getCategoryTree(val[len])
         .then(result => {
         this.options[this.flag.a].child[this.flag.b].child = result
         })

         this.getCategoryTree(val[len])
         .then(result => {
         let array = result.map((obj, index) => {
         delete obj.children
         return obj
         })
         this.options[this.flag.a].child[this.flag.b].child = array
         })
         } */
      },
      getCategoryTree (id) {
        let url = api.categoryTree
        url = id ? url + '?parentId=' + id : url
        return new Promise((resolve, reject) => {
          axios.get(url)
            .then(response => {
              const result = response.data
              if (result.success) {
                resolve(result.data)
              } else {
                reject(result)
              }
            })
        })
      },
      getCategory (id) {
        this.getCategoryTree(id)
          .then(result => {
            if (this.ruleForm.categoryDeeper === '1') {
              let array = result.map((obj, index) => {
                delete obj.child
                return obj
              })
              this.options = array
            } else {
              this.options = result
            }
          })
      },
      change () {
        this.getCategory(1)
      },
      submitForm (formName) {
        var ids = this.ruleForm.id
        var len = ids.length
        this.submitStatus = true
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var ruleForm = this.ruleForm
            ruleForm.id = ids[len - 1]
            ruleForm = format.formatString(ruleForm)
            axios.post(api.categoryAdd + '?' + ruleForm).then(response => {
              var result = response.data
              if (result.success) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.submitStatus = false
                this.$store.dispatch(types.SORTER_CLOSE_FORM)
                this.resetForm(formName)
              } else {
                this.submitStatus = false
                this.$message.error({
                  title: '错误',
                  message: result.message
                })
              }
              this.getTreeData()
            }, (err) => {
              this.$message.error({
                title: '错误',
                message: err.response.data.message
              })
              this.submitStatus = false
            })
          } else {
            this.submitStatus = false
            console.log('error submit!!')
            return false
          }
        })
      },
      updateForm (formName) {
        this.submitStatus = true
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var ruleForm = this.ruleForm
            delete ruleForm.cateText
            ruleForm = format.formatString(ruleForm)
            axios.post(api.categoryUpdate + '?' + ruleForm).then(response => {
              var result = response.data
              if (result.success) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.submitStatus = false
                this.$store.dispatch(types.SORTER_CLOSE_FORM)
                this.resetForm(formName)
              } else {
                this.submitStatus = false
                this.$message.error({
                  title: '错误',
                  message: result.message
                })
              }
            })
          } else {
            this.submitStatus = false
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    },
    mounted () {
    }
  }
</script>
<style>
  .demo-ruleForm {
    width: 440px;
  }
</style>
